Programming language subset 👋

This is a collection of code pieces that demonstrate the correct format and syntax of python code

String vs integer

String and integer are both common data types in Python

    # This is a string
    "Hello World"
    
    # This is an integer
    43 
    

Assigning (adding) a value to a variable

    myvariable = "some text"
    

Assigning (adding) a user input to a variable

    myvariable = input("Prompt text - what the user should write: ")
    

Casting a value to an integer

A user input or a string can be placed within the brackets

    myvariable = int(## Whatever needs to be converted to an integer ##)
    

Using .lower()

    # myvariable starts off as "Hello World"
    
    # This code is then run
    myvariable.lower()
    
    # myvariable is now "hello world"
    
    

fStrings and Curly Brackets

    print(f"This is a variable {var1} and another variable {var2}")
    

Mathematical operations

    *  /  +  -
    

Using simple selection

    if myvariable == "some value":
        print("Response if true")
    else:
        print("Response if false")
    

Using branching selection

    if myvariable == "some value":
        print("Response if true")
    elif myvariable == "another value":
        print("Response if also true")
    
    # As many elifs as needed can go here    
    
    else:
        print("Response if false")
    

Relational operators

These are used to test the relationship between two values

    
    ==    !=    >     <     >=    <=
    
    

While loop

Everything that happens inside of the loop must be indented from the left

    myvariable = "the value of this variable"
    
    while myvariable != "some value":
        print("Incorrect - try again")
        # Other lines of code can go here - such as asking the user to input a new value for the variable
        
    #----- Anything below here is what happens when the while loop has ended
    

while True loop

    
    while True:
        myvariable = input("Enter a value: ")
        
        if myvariable == "some value":
            print("Correct")
            break
        else:
            print("Incorrect - try again!")

    

for loop

    for i in range(0, 6):
        print(i)
    

This outputs

    0
    1
    2
    3
    4
    5
    

1 dimensional list

    mylist = ["thing 1", "thing 2", "thing 3", "thing 4", "thing 5"]
    
    print(mylist[2])
    print(mylist[4])
    

2 dimensional lists

    mylist = [
        ["apple", "fruit"], 
        ["carrot", "vegetable"], 
        ["grape", "fruit"],
        ["cabbage", "vegetable"],  
        ["pear", "fruit"]
        ]
    
    print(f"{mylist[2][0]} is a {mylist[2][1] )
    print(f"{mylist[3][0]} is a {mylist[3][1] )
    
    

Iteration through a 1D list

    for i in range(0, 6):
        print(listname[i])
    

Iteration through a 1D list

    for i in range(0, 6):
        print(f"{listname[i][0]} is a character from {listname[i][1]}")